package ssm.service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ssm.exception.XDException;
import ssm.mapper.EpisodeMapper;
import ssm.mapper.PlayRecordMapper;
import ssm.mapper.VideoMapper;
import ssm.mapper.VideoOrderMapper;
import ssm.model.entity.Episode;
import ssm.model.entity.PlayRecord;
import ssm.model.entity.Video;
import ssm.model.entity.VideoOrder;
import ssm.service.VideoOrderService;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class VideoOrderServiceImpl implements VideoOrderService {
    @Autowired
    private VideoOrderMapper videoOrderMapper;

    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private EpisodeMapper episodeMapper;

    @Autowired
    private PlayRecordMapper playRecordMapper;


    @Override
    @Transactional
    public int save(int userId, int videoId) {
        // 判断是否已经购买
        VideoOrder videoOrder = videoOrderMapper.findByuserIdAndVideoIdAndState(userId, videoId, 1);
        if (videoOrder != null) {
            return 0;
        }
        Video video = videoMapper.findById(videoId);

        VideoOrder videoOrder1 = new VideoOrder();
        videoOrder1.setCreateTime(new Date());
        videoOrder1.setOutTradeNo(UUID.randomUUID().toString());
        videoOrder1.setState(1);
        videoOrder1.setTotalFee(video.getPrice());
        videoOrder1.setUserId(userId);
        videoOrder1.setVideoId(videoId);
        videoOrder1.setVideoImg(video.getCoverImg());
        videoOrder1.setVideoTitle(video.getTitle());
        int i = videoOrderMapper.saveOrder(videoOrder1);

        // 设置默认的播放记录
        if (i == 1) {

            Episode episode = episodeMapper.findFirstEpisodeByVideoId(videoId);
            if(episode==null){
                throw  new XDException(-1,"视频没有集信息");
            }
            PlayRecord playRecord = new PlayRecord();
            playRecord.setCreateTime(new Date());
            playRecord.setEpisodeId(episode.getId());
            playRecord.setCurrentNum(episode.getNum());
            playRecord.setUserId(userId);
            playRecord.setVideoId(videoId);
            playRecordMapper.savePlayRecord(playRecord);

        }

        return i;
    }

    @Override
    public List<VideoOrder> listOrderByUserId(Integer userId) {
return videoOrderMapper.listOrderByUserId(userId);
    }
}
